package com.lbc.common.config.shiro;

import com.lbc.bean.entity.User;
import com.lbc.common.constants.Constants;
import com.lbc.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * @author xyl
 * @date 2021-03-03 10:22
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof AuthToken;
    }

    //此处使用Lazy 是因为事务不生效
    @Lazy
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        Integer userId = user.getUserId();
        //获取用户权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //在数据库中查询 , 设置角色
        info.setRoles(new HashSet<>(userService.getRolesByUserId(userId)));
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取前端传来的token
        String accessToken = (String) authenticationToken.getPrincipal();
        String id = stringRedisTemplate.opsForValue().get(Constants.REDIS_KEY_TOKEN_PREFIX + accessToken);
        if (StringUtils.isEmpty(id)){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        User user = userService.getUserById(Integer.valueOf(id));
        if (user == null){
            throw new UnknownAccountException("用户不存在!");
        }
        //传入user以及获取到的token实现自动认证
        return new SimpleAuthenticationInfo(user, accessToken, getName());
    }
}
